import Vue from 'vue'
import VueRouter from 'vue-router'
import { getItem } from '@/utils/auth.js'
const Login = () => import('@/views/login/index.vue')
const Home = () => import('@/views/home/index.vue')
const Question = () => import('@/views/question/idnex.vue')
const Video = () => import('@/views/video/index.vue')
const User = () => import('@/views/user/index.vue')
const Profile = () => import('@/views/user/profile.vue')
const Chat = () => import('@/views/user/chat.vue')
const Article = () => import('@/views/article/index.vue')
const Tabbar = () => import('@/components/app-tabbar.vue')

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    alias: '/home',
    components: {
      default: Home,
      bottom: Tabbar
    }
  },
  {
    path: '/question',
    components: {
      default: Question,
      bottom: Tabbar
    }
  },
  {
    path: '/user',
    components: {
      default: User,
      bottom: Tabbar
    },
    meta: {
      needLogin: true
    }
  },
  {
    path: '/user/profile',
    components: {
      default: Profile
    },
    meta: {
      needLogin: true
    }
  },
  {
    path: '/user/chat',
    component: Chat,
    meta: {
      needLogin: true
    }
  },
  {
    path: '/video',
    components: {
      default: Video,
      bottom: Tabbar
    }
  },
  {
    // path: '/article/:id', // 动态路由传值 加？表示id可传可不传
    path: '/article', // 路由基本传值
    component: Article
  }
]

const router = new VueRouter({
  routes
})
// 导航守卫
// 前置守卫
// 设置需要登录访问的白名单
// const withePath = ['/user', '/user/profile', '/user/chat']
router.beforeEach((to, from, next) => {
  //   console.log(to)
  // 访问限制 判断是否有token，判断是否要去登录页(限制某些页面需要登录才可访问)
  if (getItem()) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    // 1.依据路由地址的规律来限制
    // if (to.path.toLowerCase().startsWith('/user')) {
    // 2.设置白名单（创建数组）：将需要登录才可以访问的地址放到数组中
    // if (withePath.includes(to.path.toLowerCase())) {
    // 3.通过路由元配置 需要登录才可以访问的页面needLogin:true
    if (to.meta.needLogin) {
      // 需求：如果用户要跳转到其他页面，登录后应该回跳到对应的页面
      //   next('login') next()===this.$router.push()
      //   fullPath 带参数的路由
      next('login?redirect=' + to.fullPath)
    } else {
      next()
    }
  }
})
// 后置守卫
router.afterEach((to, from) => {})
// 设置访问限制，强制路由跳转，路由自身会报错（路由自身的缺陷），设置以下代码就可以解决报错问题
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return routerPush.call(this, location).catch(error => error)
}
export default router
